<template>
  <BasicModal v-bind="$attrs" @register="registerModal" title="添加设备" @ok="handleSubmit">
    <BasicForm @register="registerForm">
    </BasicForm>
  </BasicModal>
</template>
<script lang="ts" setup>
import { ref } from 'vue';

import { addDeviceFormSchema } from './device.data';
import { BasicForm, useForm } from '@/components/Form';
import { BasicModal, useModalInner } from '@/components/Modal';

import { addDeviceBase } from '@/api/collection/device/index'
import { message } from 'ant-design-vue';

defineOptions({ name: 'HandleModal' });
defineProps({
  code: {
    type: String,
  },
})
const emit = defineEmits(['success', 'register']);

const rowId = ref('');

const [registerForm, { resetFields, validate, setFieldsValue }] = useForm({
  labelWidth: 100,
  baseColProps: { span: 24 },
  schemas: addDeviceFormSchema,
  showActionButtonGroup: false,
  actionColOptions: {
    span: 23,
  },
});

const [registerModal, { setModalProps, closeModal }] = useModalInner(async ({ type, id }) => {
  rowId.value = id;
  resetFields();
  if (type) {
    setFieldsValue({ type })
  }
  setModalProps({ confirmLoading: false });
});

async function handleSubmit() {
  try {
    const values = await validate();

    setModalProps({ confirmLoading: true });
    const params = { ...values, alarmRecordId: rowId.value }
    addDeviceBase(params).then(res => {
      message.success('添加成功')
      closeModal();
      emit('success', { values: { ...values, alarmRecordId: rowId.value } });
    })
  } finally {
    setModalProps({ confirmLoading: false });
  }
}
</script>
<style scoped></style>